package com.yaorange.module.system.controller;


import com.yaorange.exception.ValidateException;
import com.yaorange.module.system.service.SysRoleService;
import com.yaorange.pojo.SysRole;
import com.yaorange.response.Result;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/sys/role")
@Validated
@Slf4j
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 新增角色
     */
    @PostMapping
    public Result<SysRole> createRole(@Valid @RequestBody SysRole sysRole) {
        sysRoleService.save(sysRole);
        return Result.success();
    }

    /**
     * 查询所有角色（支持分页）
     */
    @GetMapping
    public Result<List<SysRole>> getAllRoles() {
        log.info("查询所有角色");
        List<SysRole> roles = sysRoleService.findAll();
        return Result.success(roles);
    }

    /**
     * 根据 ID 查询角色
     */
    @GetMapping("/{id}")
    public Result<SysRole> getRoleById(@PathVariable Long id) {
        SysRole role = sysRoleService.findById(id);
        return Result.success(role);
    }

    /**
     * 更新角色信息
     */
    @PutMapping("/{id}")
    public Result updateRole(@PathVariable Long id,
                                      @Valid @RequestBody SysRole roleDetails) {
        log.info("更新角色信息"+roleDetails);
        if(id == null){
            throw  new ValidateException("缺少参数，不能修改");
        }
        sysRoleService.update(id, roleDetails);
        return Result.success();
    }

    /**
     * 删除角色
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteRole(@PathVariable Long id) {
        log.info("删除角色 id:"+id);
        if(id == null){
            throw  new ValidateException("缺少参数，不能删除");
        }
        sysRoleService.deleteById(id);
        return Result.success();
    }

    @GetMapping("/permission/{roleId}")
    public Result<List<Long>> getPermissionsByRoleId(@PathVariable Long roleId) {
        log.info("查询角色权限 roleId:"+roleId);
        return Result.success(sysRoleService.findPermissionsByRoleId(roleId));
    }

    @PostMapping("/permission/{roleId}")
    public Result updateRolePermission(@RequestBody List<Long> permissionIds, @PathVariable Long roleId) {
        log.info("更新角色权限 permissionIds:"+permissionIds+" roleId:"+roleId);
        sysRoleService.grantPermission(permissionIds,roleId);
        return Result.success();
    }

    @DeleteMapping
    public Result deleteRole(@RequestBody List<Long> roleIds) {
        log.info("删除角色 roleIds:"+roleIds);
        sysRoleService.deleteByIds(roleIds);
        return Result.success();
    }
}
